﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

/// <summary>
///Eneity 的摘要说明
/// </summary>
public class Eneity
{
	public Eneity()
	{
        List<UserTable> TablesList = new List<UserTable>();
        SqlConnection conn = new SqlConnection("Data Source=IFCA-LIUJU;Initial Catalog=MyFavorites;Integrated Security=True;");
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(@"
select 
    t.name as TableName,t.object_id as TableID,c.name as PrimaryKeyName
from sys.tables t
inner join sys.columns c on c.object_id=t.object_id and c.is_identity=1
where type='U'
order by t.object_id,c.column_id

select 
    tab.name as TableName,tab.object_id as TableID,
    c.name as ColumnName,c.column_id as ColumnID,c.is_nullable as Nullable,c.is_identity as IsPrimaryKey,
    t.name as TypeName
from sys.columns c
inner join sys.tables tab on tab.object_id=c.object_id
inner join sys.types t on t.system_type_id=c.system_type_id and t.user_type_id=c.user_type_id
where tab.type='U'
order by tab.object_id,c.column_id
", conn);
        adapter.Fill(ds);
        DataTable tables = ds.Tables[0];
        DataTable columns = ds.Tables[1];
        foreach (DataRow row in tables.Rows)
        {
            UserTable ut = new UserTable();
            ut.TableName = row["TableName"].ToString();
            ut.PrimaryKeyName = row["PrimaryKeyName"].ToString();
            List<TableColumn> TableColumnList = new List<TableColumn>();
            foreach (DataRow column in columns.Rows)
            {
                if (column["TableName"].ToString() == ut.TableName)
                {
                    TableColumn tc = new TableColumn();
                    tc.TableName = column["TableName"].ToString();
                    tc.ColumnName = column["ColumnName"].ToString();
                    tc.Nullable = bool.Parse(column["Nullable"].ToString());
                    tc.TypeName = column["TypeName"].ToString();
                    TableColumnList.Add(tc);
                }
            }
            ut.Columns = TableColumnList;
            TablesList.Add(ut);
        }
	}
}
public class UserTable
{
    public string TableName;
    public string PrimaryKeyName;
    public List<TableColumn> Columns;
}
public class TableColumn
{
    public string TableName;
    public string ColumnName;
    public string TypeName;
    public bool Nullable;
}